<template>
  <div class="login">
    <van-nav-bar title="登录" />
    <!-- 登录表单 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="mobile"
        required
        label="手机号"
        placeholder="请输入手机号"
        :rules="[
          { required: true, message: '手机号不能为空' },
          { validator, message: '请输入正确的11位手机号' },
        ]"
      />
      <!-- error-message="验证码格式错误" -->
      <van-field
        v-model="code"
        required
        label="验证码"
        placeholder="请输入验证码"
        :rules="[
          { required: true, message: '验证码不能位空' },
          { pattern, message: '请输入正确的6位验证码' },
        ]"
      />
      <div class="login_btn">
        <van-button type="info">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
// 一、导入模块
import { postLogin } from '@/api/user.js'
import { mapMutations } from 'vuex'
export default {
  name: 'Login',
  data() {
    return {
      mobile: '18720935448',
      code: '246810',
      pattern: /\d{6}/,
    }
  },

  methods: {
    // 二、登录方法
    async onSubmit() {
      // 2.1 loading动画
      this.$toast.loading({
        duration: 0, // 持续展示 toast,永远不会关闭
        overlay: true, // 整体添加一个遮罩
        message: '拼命加载中...',
        forbidClick: true,
      })
      try {
        // 2.2 发送请求
        const { data } = await postLogin({ mobile: this.mobile, code: this.code })
        // console.log(data)
        // 2.3 保存token,成功提示信息,跳转到首页
        this.setTokenInfo(data.data)
        setTimeout(() => {
          this.$toast.success('登录成功')
          // 优化:如果是导航守卫拦截过来的跳转,重新登录之后应该跳回被拦截的页面
          const backto = this.$route.query.backto || '/'
          this.$router.push(backto)
        }, 500)
      } catch {
        this.$toast.fail('登录失败')
      }
    },

    // 三、自定义校验规则
    validator(val) {
      return /^1[3-9]\d{9}$/.test(val)
    },

    // 四、映射user中获取token信息的方法
    ...mapMutations('user', ['setTokenInfo']),
  },
}
</script>

<style lang="scss" scoped>
.login {
  .login_btn {
    padding: 20px;
    .van-button {
      width: 100%;
      color: #fff;
      border-radius: 5px;
    }
  }
  /deep/.van-field--error .van-field__control,
  /deep/.van-field--error .van-field__control::placeholder {
    color: #ccc;
  }
}
</style>
